let router = require('../router/Router');
const { BusiError, SysError, ErrorResult } = require('../exception/exception');
let friendService = require('../service/friendService');
let Token = require('../token');

router.post('/auth/queryFriends', function (req, resp) {
    let page = req.body.page;
    if (page < 0 || isNaN(page)) page = 0;
    let token = req.body.token;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token);
        let uidObj = JSON.parse(uid);
        if (uidObj.uid) {
            uid = uidObj.uid;
        }
    } catch (e) {
        uid = -1;
        resp.send({ code: 500, list: [] });
        return;

    }



    friendService.queryFriends(uid, page).then((list) => {
        resp.send({ msg: "success", code: 200, list: list });
    }).catch(err => {
        console.logw("err:", err);
        resp.send(new ErrorResult(err));
    });

});

router.post('/auth/isFriend', function (req, resp) {

    let ownerUid = req.body.ownerUid;
    let token = req.body.token;
   
    let n1 = Number(ownerUid), n2 = Number(req.uid);
    let key = n1 + '_' + n2;
    if (n1 > n2) key = n2 + '_' + n1;
    friendService.isFriend(req.uid, ownerUid).then((bFriend) => {
        resp.send({ code: 200, bFriend: bFriend });
    }).catch(err => {
        console.logw("err:", err);
        resp.send(new ErrorResult(err));
    });

});


router.post('/auth/searchFriend', function (req, resp) {
    let uid0 = req.uid;
    friendService.searchFriend(uid0, uid0).then((ret) => {
        if (ret == null) {
            resp.send({ code: 200, msg: "记录不存在" });
            return;
        }
        ret.code = 200;
        resp.send(ret);
    }).catch(err => {
        console.logw("err:", err);
        resp.send(new ErrorResult(err));
    });
});

router.post('/auth/applyFriend', function (req, resp) {
    let friendUid = req.body.friendUid;
   
    friendService.applyBeFriend(req.uid, friendUid).then((ret) => {
        resp.send({ code: 200, msg: '操作成功' });
    }).catch(err => {
        console.logw("err:", err);
        resp.send(new ErrorResult(err));
    });
});



router.post('/auth/agreeFriend', function (req, resp) {
    let friendUid = req.body.friendUid;

    friendService.agreeFriend(req.uid, friendUid).then((ret) => {
        resp.send({ code: 200, msg: '操作成功', data: ret });
    }).catch(err => {
        console.logw("err:", err);
        resp.send(new ErrorResult(err));
    });
});


router.post('/auth/deleteFriend', function (req, resp) {
    let friendUid = req.body.friendUid;
    if (req.uid === friendUid) {
        resp.send({ code: 500, msg: 'can not delete self' });
        return;
    }

    friendService.deleteFriend(req.uid, friendUid).then((ret) => {
        resp.send({ code: 200, msg: '操作成功', data: ret});
    }).catch(err => {
        console.logw("err:", err);
        resp.send(new ErrorResult(err));
    });
});
